package com.andy.blog.dal.service.impl;

import com.andy.blog.common.enums.DeleteTypeEnum;
import com.andy.blog.common.exception.BlogServiceException;
import com.andy.blog.common.reponse.BlogResultCode;
import com.andy.blog.common.utils.SecurityUtils;
import com.andy.blog.common.utils.TransformUtils;
import com.andy.blog.dal.domain.MessageDO;
import com.andy.blog.dal.mapper.MessageMapper;
import com.andy.blog.dal.service.MessageDalService;
import com.andy.blog.dal.vo.MessageVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by andy on 2023/8/4 22:05
 */
@Service
public class MessageDalServiceImpl implements MessageDalService {

    @Resource
    private MessageMapper messageMapper;


    @Override
    public List<MessageDO> selectList(MessageVO messageVO) {
        LambdaQueryWrapper<MessageDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(MessageDO::getIsDeleted, DeleteTypeEnum.DELETE_N.getCode());
        return messageMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public void insertMessage(MessageVO messageVO) {
        MessageDO messageDO = TransformUtils.transform(messageVO, MessageDO.class);

        // messageDO.setCreateBy(SecurityUtils.getUsername());
        messageDO.setIsDeleted(DeleteTypeEnum.DELETE_N.getCode());

        try {
            messageMapper.insert(messageDO);
        } catch (Exception e) {
            throw new BlogServiceException(BlogResultCode.BLOG_000100, e);
        }
    }

    @Override
    public void updateMessage(MessageVO messageVO) {
        MessageDO messageDO = TransformUtils.transform(messageVO, MessageDO.class);

        messageDO.setUpdateBy(SecurityUtils.getUsername());

        try {
            messageMapper.updateById(messageDO);
        } catch (Exception e) {
            throw new BlogServiceException(BlogResultCode.BLOG_000101, e);
        }
    }

    @Override
    public IPage<MessageDO> selectPage(MessageVO messageVO) {
        LambdaQueryWrapper<MessageDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .like(StringUtils.isNotBlank(messageVO.getNickName()), MessageDO::getNickName, messageVO.getNickName())
                .orderByDesc(MessageDO::getCreateTime);

        IPage<MessageDO> page = new Page<>(messageVO.getPageNum(), messageVO.getPageSize());

        return messageMapper.selectPage(page, lambdaQueryWrapper);
    }

    @Override
    public void deleteById(Long id) {
        try {
            messageMapper.deleteById(id);
        } catch (Exception e) {
            throw new BlogServiceException(BlogResultCode.BLOG_000102, e);
        }
    }
}

